import React, { useEffect, Fragment } from 'react';
import { connect } from 'umi';
import { Form, Input, Button, Table, Card, DatePicker } from 'antd';
import { eventTrack } from '@/utils/track';
// import { QuickForm, utils } from 'vv-frontend-components';
import { utils } from 'vv-frontend-components';
import moment from 'moment';
import Locale from '@/utils/locale';
// import DateRange from '@/components/DateRange';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import updateQuery from '@/utils/formValuesToQuery';
// import request from '@/utils/request';
import { formatSecond, isCurMonth, download } from '@/utils/utils';
import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import { withRoutePage } from '@/utils/enhanceUtils';
import { Pagination } from '@/components';
import { CompanyDepartPlus } from '@/containers';
import styles from './attendStat.less';

const { locale } = new Locale('stat.attendStat');
const { deepTrim } = utils;
const { MonthPicker } = DatePicker;

const List = ({ form, attendStat, loading, dispatch, location, match, route }) => {
    // const [tabTitle, setTabTitle] = useState('');
    const {
        query: {
            // id,
            companyId,
            departmentId
            // dateType
        }
    } = location;
    const { getFieldsValue, getFieldDecorator } = form;
    const { pagination, data } = attendStat;
    const { authCode } = new AuthCode(route.code);
    const renderLeave = text => {
        const value = Number(text);
        if (!value) return text;
        // const day = Math.floor(value / 8);
        // const hours = value % 8;
        // return `${day ? `${day}天` : ''}${hours % 8 ? `${hours}小时` : ''}`;
        return formatSecond(value * 60, true, false, 8);
    };

    const renderAttend = text => `${text}天`;

    const columns = [
        {
            title: '工号',
            dataIndex: 'userNo',
            key: 'userNo',
            fixed: 'left'
        },
        {
            title: '姓名',
            dataIndex: 'employedName',
            key: 'employedName',
            width: 80,
            fixed: 'left'
        },
        {
            title: '组织机构',
            dataIndex: 'departmentName',
            key: 'departmentName',
            width: 100,
            fixed: 'left'
        },
        {
            title: '出勤',
            children: [
                {
                    title: '应出勤',
                    dataIndex: 'attendanceDay',
                    key: 'attendanceDay',
                    render(text) {
                        return renderAttend(text);
                    }
                },
                {
                    title: '实际出勤',
                    dataIndex: 'actualAttendanceDay',
                    key: 'actualAttendanceDay',
                    render(text) {
                        return renderAttend(text);
                    }
                }
            ]
        },
        {
            // title: '请假/调休（小时）',
            title: '请假/调休',
            children: [
                {
                    title: '事假',
                    dataIndex: 'affairLeave',
                    key: 'affairLeave',
                    render(text) {
                        return renderLeave(text);
                    }
                },
                {
                    title: '调休',
                    dataIndex: 'paidLeave',
                    key: 'paidLeave',
                    render(text) {
                        return renderLeave(text);
                    }
                },
                {
                    title: '年假',
                    dataIndex: 'annualLeave',
                    key: 'annualLeave',
                    render(text) {
                        return renderLeave(text);
                    }
                },
                {
                    title: '病假',
                    dataIndex: 'sickLeave',
                    key: 'sickLeave',
                    render(text) {
                        return renderLeave(text);
                    }
                },
                {
                    title: '产护假',
                    dataIndex: 'maintenanceLeave',
                    key: 'maintenanceLeave',
                    render(text) {
                        return renderLeave(text);
                    }
                },
                {
                    title: '其他',
                    dataIndex: 'orthersLeave',
                    key: 'orthersLeave',
                    render(text) {
                        return renderLeave(text);
                    }
                }
            ]
        },
        {
            title: '加班',
            children: [
                {
                    title: '工作日',
                    dataIndex: 'workOvertimeMinute',
                    key: 'workOvertimeMinute'
                },
                {
                    title: '休息日',
                    dataIndex: 'overtimeRestTimeMinute',
                    key: 'overtimeRestTimeMinute'
                },
                {
                    title: '节假日',
                    dataIndex: 'workOvertimeHolidaysMinute',
                    key: 'workOvertimeHolidaysMinute'
                }
            ]
        },
        {
            title: '异常',
            children: [
                {
                    title: '迟到1',
                    key: 'late1Num',
                    width: 100,
                    render(text, record) {
                        const find =
                            record.summaryAbnormVos && record.summaryAbnormVos.find(item => item.code === 'lateOne');
                        return (
                            <div className="not-wrap-text">
                                {find ? find.countNum : 0} 次，
                                <br />
                                {find ? find.minute : 0} 分钟
                            </div>
                        );
                    }
                },
                {
                    title: '迟到2',
                    key: 'late2Num',
                    width: 100,
                    render(text, record) {
                        const find =
                            record.summaryAbnormVos && record.summaryAbnormVos.find(item => item.code === 'lateTwo');
                        return (
                            <div className="not-wrap-text">
                                {find ? find.countNum : 0} 次，
                                <br />
                                {find ? find.minute : 0} 分钟
                            </div>
                        );
                    }
                },
                {
                    title: '早退1',
                    key: 'earlyLeave1Num',
                    width: 100,
                    render(text, record) {
                        const find =
                            record.summaryAbnormVos && record.summaryAbnormVos.find(item => item.code === 'earlyOne');
                        return (
                            <div className="not-wrap-text">
                                {find ? find.countNum : 0} 次，
                                <br />
                                {find ? find.minute : 0} 分钟
                            </div>
                        );
                    }
                },
                {
                    title: '早退2',
                    key: 'earlyLeave2Num',
                    width: 100,
                    render(text, record) {
                        const find =
                            record.summaryAbnormVos && record.summaryAbnormVos.find(item => item.code === 'earlyTwo');
                        return (
                            <div className="not-wrap-text">
                                {find ? find.countNum : 0} 次，
                                <br />
                                {find ? find.minute : 0} 分钟
                            </div>
                        );
                    }
                },
                {
                    title: '缺卡',
                    dataIndex: 'missCard',
                    key: 'missCard',
                    render(text, record) {
                        const find =
                            record.summaryAbnormVos && record.summaryAbnormVos.find(item => item.code === 'lackCard');
                        return find ? find.countNum : 0;
                    }
                },
                {
                    title: '缺勤',
                    dataIndex: 'absenceDuty',
                    key: 'absenceDuty',
                    render(text, record) {
                        const find =
                            record.summaryAbnormVos && record.summaryAbnormVos.find(item => item.code === 'absence');
                        return find ? find.countNum : 0;
                    }
                }
            ]
        }
    ];
    const getEndTime = month => {
        if (month) {
            if (isCurMonth(month)) {
                return moment().format('YYYY-MM-DD');
            }
            return month.endOf('month').format('YYYY-MM-DD');
        }
        return '';
    };
    const getParams = () => {
        const { companyDepart = {}, userNameForm, month } = getFieldsValue();

        const payload = {
            companyCode: companyDepart?.companyId || '',
            departmentCode: companyDepart?.departmentId || '',
            userName: userNameForm,
            startTime: month ? month.startOf('month').format('YYYY-MM-DD') : '',
            endTime: getEndTime(month),
            pageNo: pagination.current,
            pageSize: pagination.pageSize
        };
        return payload;
    };
    const fetchList = () => {
        // const { month } = getFieldsValue();
        // if (month) setTabTitle(month.startOf('month').format('YYYY年MM月出勤统计'));
        dispatch(
            deepTrim({
                type: 'attendStat/fetchList',
                payload: getParams()
            })
        );
    };
    const handleSubmit = async e => {
        // e.preventDefault();
        const { eType } = e;
        const { companyDepart, month, userNameForm } = form.getFieldsValue();
        if (attendStat.pagination.current !== 1) {
            await dispatch({
                type: 'attendStat/save',
                payload: {
                    pagination: {
                        ...attendStat.pagination,
                        current: 1
                    }
                }
            });
        } else {
            fetchList();
        }

        const queryObj = {
            ...location.query,
            companyId: eType === 'reset' ? '' : companyDepart && companyDepart.companyId,
            departmentId: eType === 'reset' ? '' : companyDepart && companyDepart.departmentId,
            userName: userNameForm,
            dateType: 'month',
            startTime: month ? month.startOf('month').format('YYYY-MM-DD') : '',
            endTime: getEndTime(month)
        };

        updateQuery(match.path, queryObj);
        // 埋点
        eventTrack({
            eventName:
                eType === 'search'
                    ? 'personnel_management_attendance_attendStat_search_click'
                    : 'personnel_management_attendance_attendStat_reset_click',
            eventProps: {
                key_works: eType === 'search' ? JSON.stringify(queryObj) : null
            }
        });
    };

    const changeCurrent = async e => {
        await dispatch({
            type: 'attendStat/save',
            payload: {
                pagination: {
                    ...attendStat.pagination,
                    ...e
                }
            }
        });
    };
    const handleExport = () => {
        const { pageNo, pageSize, ...other } = getParams();
        download({
            getData: () =>
                dispatch({
                    type: 'attendStat/fetchExport',
                    payload: deepTrim(other)
                })
        });
        // 埋点
        eventTrack({
            eventName: 'personnel_management_attendance_attendStat_export_click',
            eventProps: {
                label: '出勤统计-导出'
            }
        });
    };

    // 每当分页数或页数改变时均应该重新请求表格数据
    useEffect(() => {
        fetchList();
    }, [pagination.current, pagination.pageSize]);

    const initCompanyDepart = companyId || departmentId ? { companyId, departmentId } : undefined;

    return (
        <PageHeaderWrapper>
            <Fragment>
                <Card
                    bordered={false}
                    title="检索条件"
                    extra={
                        <Fragment>
                            <AuthComponent code={authCode('export')}>
                                <Button
                                    style={{ marginLeft: '5px' }}
                                    onClick={handleExport}
                                    disabled={loading.effects['attendStat/fetchList']}
                                >
                                    导出
                                </Button>
                            </AuthComponent>
                        </Fragment>
                    }
                >
                    <Form
                        layout="inline"
                        style={{ marginBottom: 16 }}
                        onSubmit={e => {
                            e.preventDefault();
                            handleSubmit({
                                eType: 'search'
                            });
                        }}
                    >
                        <Form.Item label="机构" className={styles.temp}>
                            {getFieldDecorator('companyDepart', {
                                initialValue: initCompanyDepart
                            })(<CompanyDepartPlus />)}
                        </Form.Item>
                        <Form.Item label={locale('yg')}>
                            {getFieldDecorator('userNameForm', {
                                initialValue: ''
                            })(<Input placeholder="输入姓名" allowClear />)}
                        </Form.Item>
                        <Form.Item label="考勤月">
                            {getFieldDecorator('month', {
                                initialValue: moment()
                            })(<MonthPicker allowClear={false} format="YYYY-MM" />)}
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                搜索
                            </Button>
                        </Form.Item>
                    </Form>
                    <Table
                        bordered
                        columns={columns}
                        loading={loading.models.attendStat}
                        dataSource={data}
                        onChange={changeCurrent}
                        rowKey="id"
                        scroll={{ x: 'max-content' }}
                        pagination={false}
                    />
                    <Pagination onChange={changeCurrent} {...pagination} loading={loading.models.attendStat} />
                </Card>
            </Fragment>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect(({ attendStat, loading }) => ({
        attendStat,
        loading
    }))(Form.create()(List))
);
